/**
 * @desc user-task
 * @author DragonTeam <https://www.bpmport.com>
 * @since 2024/10/31 16:15
 */
import type { BaseNodeBO } from '@/types'
import type { BpmnElement } from '@/types/bpmn-node'
import { createElement } from '@/data-transform/bpmn-transform/utils'

// bpmn 对应的特殊业务节点属性处理部分
export function transformBpmnUserTask(nodeBo: BaseNodeBO, element: BpmnElement) {
  const extensionElements = createElement('bpmn:ExtensionElements', {
    values: [
    ],
  })
  element.set('extensionElements', extensionElements)

  // 审批用户、角色绑定
  const { assigneeType, approvalObject, candidateUsers, candidateGroups } = nodeBo
  if (assigneeType) {
    extensionElements.values.push(createElement('AssigneeType', { body: assigneeType }))
  }

  if (approvalObject === 1) {
    element.set('assignee', '${starterCode}')
  }
  else if (approvalObject === 2) {
    element.set('candidateUsers', (candidateUsers as any[])?.map(i => i.code).join(','))
  }
  else if (approvalObject === 3) {
    element.set('candidateGroups', (candidateGroups as any[])?.map(i => i.code).join(','))
  }

  // 操作项配置
  if ((nodeBo.authPoints as any[])?.length) {
    extensionElements.values.push(
      createElement('AuthPoint', { body: JSON.stringify(nodeBo.authPoints) }),
    )
  }

  // 多实例审批配置
  const { approvalMethod, completionConditionType, completionConditionCompare, completionConditionNum, completionConditionExpression } = nodeBo
  if (!approvalMethod)
    return

  const multiInstanceLoopCharacteristics = createElement('bpmn:MultiInstanceLoopCharacteristics', {
    collection: `$\{${nodeBo.id}}`,
    elementVariable: nodeBo.id,
  })
  element.set('loopCharacteristics', multiInstanceLoopCharacteristics)

  // 依次审批（串行）
  if (approvalMethod === 1) {
    multiInstanceLoopCharacteristics.set('isSequential', true)
    return
  }

  // 并行（区分 或签 和 会签）
  multiInstanceLoopCharacteristics.set('isSequential', false)

  // 或签
  if (approvalMethod === 3) {
    multiInstanceLoopCharacteristics.set(
      'completionCondition',
      createElement('bpmn:FormalExpression', { body: '${nrOfCompletedInstances > 0}' }),
    )
    return
  }

  // 会签
  multiInstanceLoopCharacteristics.set('type', completionConditionType)
  multiInstanceLoopCharacteristics.set('elementVariable', 'user')
  if (completionConditionType === 'all') {
    return
  }

  const condition = createElement('bpmn:FormalExpression', { body: '' })
  if (completionConditionType === 'expression') {
    condition.set('body', completionConditionExpression || '')
  }
  else if (completionConditionType === 'percentage') {
    condition.set('body', `\${(nrOfCompletedInstances / nrOfInstances) * 100 ${completionConditionCompare} ${completionConditionNum}}`)
  }
  else {
    condition.set('body', `\${nrOfCompletedInstances ${completionConditionCompare} ${completionConditionNum}}`)
  }
  multiInstanceLoopCharacteristics.set('completionCondition', condition)
}
